package org.example.zk;

import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.data.Stat;

import java.util.List;

/**
 * zk客户端操作类
 */
public class ZkClient {

    public static ZkClient instance = new ZkClient();

    public CuratorFramework client;

    public ZkClient() {
        client = ClientFactory.createSimple("localhost:2181");
        client.start();
    }


    /**
     * 判断node是否存在
     * @param path
     * @return
     */
    public boolean nodeExists(String path) {
        try {
            Stat stat = client.checkExists().forPath(path);
            if (stat != null)
                return true;
            return false;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 创建永久节点
     * @param path
     * @return
     */
    public void createNode(String path) {
        try {
            String forPath = client.create()
                    .creatingParentsIfNeeded()
                    .withMode(CreateMode.PERSISTENT)
                    .forPath(path);
        }
        catch (KeeperException.NodeExistsException e) {
            // TODO 无需重复创建，节点已经存在
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 创建临时带序号的节点
     * @param path
     * @return
     */
    public String createSeqNode(String path) {
        try {
            String path1 = client.create()
                    .creatingParentsIfNeeded()
                    .withMode(CreateMode.EPHEMERAL_SEQUENTIAL)
                    .forPath(path);
            return path1;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 返回子节点
     * @param path
     * @return
     */
    public List<String> getChildrenNode(String path) {
        try {
            return client.getChildren().forPath(path);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 删除节点
     * @param path
     */
    public void deleteNode(String path) {
        try {
            client.delete().forPath(path);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
